package atri.controller;

import atri.common.Result;
import atri.mapper.UserMapper;
import atri.model.User;
import atri.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController

public class UserController{


    @Autowired
    public UserService service;
    @Autowired
    public UserMapper mapper;
//    @Autowired
//    public BlogMapper b_mapper;
//    @Autowired
//    public BlogService blogService;
//    @Autowired
//    public CommentService commentService;
    @PostMapping("/user")
    public Result save (@RequestBody User student){
        int a =mapper.insert(student);
        if(a!=0)
        {return Result.success(service.getUserByName(student.getName()));}
        else
        {return Result.fail();}
    }

    @DeleteMapping("/user/{id}")
    public Result remove(@PathVariable int id){
            Boolean a = service.removeById(id);
            if(a)
            {return Result.success(a);}
            else
            {return Result.fail();}
    }

    @PutMapping("/user")
    public Result updateById(@RequestBody User user){
        Boolean a = service.updateById(user);
        if(a)
        {return Result.success(a);}
        else
        {return Result.fail();}
    }

    @GetMapping("/user")
    public Result Getlist(){
        List<User> s = new ArrayList<>();
        s=service.list();
        if(s!=null)
        {return  Result.success(s);}
        else
        {return Result.fail();}
    }

    @GetMapping("/user/{name}")
    public Result GetByid(@PathVariable("name") String name){
        List<User> user = new ArrayList<>();
        user = service.getUserByName_true(name);
        if(user != null)
        {return Result.success(user);}
        else
        {return Result.fail();}
    }
    @PostMapping("/login")
    public Result login(@RequestBody User user, HttpSession session){
        boolean flag = service.login(user.getId(),user.getPassword());
        if(flag)
        {   session.setAttribute("name",user.getName());
            return Result.success(service.getById(user.getId()));}
        else
        {return Result.fail();}
    }

}
